import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue2'
import { resolve } from 'path'
import { exec } from 'child_process'

// 自定义插件：构建完成后执行copy.bat
const copyFilesPlugin = () => {
  return {
    name: 'copy-files',
    closeBundle() {
      console.log('构建完成，正在复制文件...')
      exec('cmd /c copy.bat', { cwd: __dirname }, (error, stdout, stderr) => {
        if (error) {
          console.error('复制文件失败:', error)
          return
        }
        if (stderr) {
          console.error('复制文件警告:', stderr)
        }
        console.log('文件复制完成:', stdout)
      })
    }
  }
}

export default defineConfig({
  plugins: [vue(), 
    copyFilesPlugin()
  ],
  build: {
    // 输出目录设置为上级目录的browser-extension-interceptor
    outDir: './dist',
    // 清空输出目录
    emptyOutDir: false,
    // 资源目录设置为libs，这样JS会输出到libs/js，CSS会输出到libs/css
    assetsDir: 'libs',
    // 多入口配置
    rollupOptions: {
      input: {
        options: resolve(__dirname, 'public/options.html'),
        popup: resolve(__dirname, 'public/popup.html'),
        popup_summary: resolve(__dirname, 'public/popup_summary.html')
      },
      output: {
        // 自定义输出文件名
        entryFileNames: (chunkInfo) => {
          return 'libs/js/[name].[hash].js'
        },
        chunkFileNames: 'libs/js/[name].[hash].js',
        assetFileNames: (assetInfo) => {
          if (assetInfo.name.endsWith('.css')) {
            return 'libs/css/[name].[hash].css'
          }
          return 'libs/[name].[hash].[ext]'
        }
      }
    }
  },
  resolve: {
    alias: {
      '@': resolve(__dirname, 'src')
    }
  }
})